
import * as Blockly from 'blockly/core'
import { getAllTableList} from '../utils/component'
import { getContextText} from '../utils/block'

Blockly.Extensions.register('dynamic_table_extension',
  function () {
    this.getInput('TABLE_INPUT')
      .appendField(new Blockly.FieldDropdown(
        function () {
          var options = []
          // 获取页面所有的表单
          let comList = getAllTableList()

          if (!comList.length) {
            options = [['没有数据', 'noData']]
            return options
          }
          for (var i = 0; i < comList.length; i++) {
            const com = comList[i]
            const dateString = `${com.name}（${com.key}）`
            options.push([dateString, com.key])
          }
          return options
        }), 'Component')
  })





// 1---------取消表格自动查询-------------------

const cancelJson = {
  type: 'table_cancel_data',
  message0: '取消表格自动查询 %1',
  args0: [
    // 动态生成选项
    {
      'type': 'input_dummy',
      'name': 'TABLE_INPUT'
    }
  ],
  extensions: ['dynamic_table_extension'],
  previousStatement: true,
  nextStatement: true,
  inputsInline: true,
  style: 'action_blocks',
  tooltip: '在列表初始化ready的时候执行该方法，使列表取消自动查询功能',
  helpUrl: ''
}

// 创建积木
Blockly.Blocks['table_cancel_data'] = {
  init: function () {
    this.jsonInit(cancelJson)
  }
}

Blockly.JavaScript['table_cancel_data'] = function (block) {
  const compVar = block.getFieldValue('Component')
  const context = getContextText(block, compVar)
  let code = `${context}.getComponent('${compVar}').dispatch('cancelData')`
  return code + '\n'
}


// 3----------------------------设置表格选中/取消选中记录--------------
const selectJson = {
  type: 'table_set_select',
  message0: '设置表格 %1%2记录%3 参数%4',
  args0: [
    {
      'type': 'input_dummy',
      'name': 'TABLE_INPUT'
    },
    {
      'type': 'field_label_serializable',
      'name': 'SELECT_TYPE',
      'text': '选中'
    },
    {
      type:'input_value',
      name: 'SELECT_LIST',
      check: 'Array',
    },
    {
      type:'field_input',
      name: 'SELECT_KEY',
      check:'String',
      text: 'id'
    }
  ],
  extensions: ['dynamic_table_extension'],
  previousStatement: true,
  nextStatement: true,
  inputsInline: true,
  style: 'action_blocks',
  tooltip: '选中或者取消复选框记录(参数作为唯一标志),参数默认是id也可以自定义',
  helpUrl: ''
}

// 创建积木
Blockly.Blocks['table_set_select'] = {
  init: function () {
    this.jsonInit(selectJson)
  }
}

Blockly.JavaScript['table_set_select'] = function (block) {
  const compVar = block.getFieldValue('Component')
  const context = getContextText(block, compVar)
  const selectFlag = block.getFieldValue('SELECT_TYPE') === '选中'
  const selectList = Blockly.JavaScript.valueToCode(block, 'SELECT_LIST',
    Blockly.JavaScript.ORDER_COMMA) || '[]'
  const selectKey = Blockly.JavaScript.quote_(block.getFieldValue ('SELECT_KEY')) || '\'id\''
  let code = `(await ${context}.getComponentSync('${compVar}')).setSelected(${selectList}, ${selectKey}, ${selectFlag})`
  return code + '\n'
}
